<?php
/**
 * Created by : PhpStorm
 * User: 阿城 <479468212@qq.com>
 * Date: 2019/12/27
 * Time: 15:02
 */
namespace app\common\middleware;

use think\facade\Request;
use app\util\ReturnCode;

class PreventConcurrent {

    /**
     * 同一路由小于规定时间内访问视为并发访问
     * @param \think\facade\Request $request
     * @param \Closure $next
     * @param $second
     * @return \think\response\Json
     */
    public function handle($request, \Closure $next, $second = 5) {
        $passSecond = $second;
        if ($passSecond <= 0) {
            return $next($request);
        }
        $userInfo = $request->USER_INFO;
        if(empty($userInfo)){
            $key = $request->ip(true);
        }else{
            $key = $userInfo['id'];
        }
        $path = app('http')->getName().config('route.pathinfo_depr').Request::controller().config('route.pathinfo_depr').Request::action();
        $preventConcurrentKey = $key.$path;
        if (cache("preventConcurrent:$preventConcurrentKey")) {
            return json([
                'code' => ReturnCode::SYSTEM_ERROR,
                'msg'  => '操作过于频繁，请等待'.($second).'秒后再试',
                'data' => []
            ]);
        }
        cache("preventConcurrent:$preventConcurrentKey", 'access', $passSecond);
        return $next($request);
    }

}
